package com.greate.community.controller;

import com.greate.community.constant.CommunityConstant;
import com.greate.community.constant.ExpType;
import com.greate.community.entity.Event;
import com.greate.community.entity.Result;
import com.greate.community.event.EventProducer;
import com.greate.community.jwt.JwtUser;
import com.greate.community.service.DiscussPostService;
import com.greate.community.service.LikeService;
import com.greate.community.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 点赞
 */
@Slf4j
@RestController
public class LikeController extends BaseController implements CommunityConstant {

    @Autowired
    private LikeService likeService;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DiscussPostService discussPostService;

    /**
     * 点赞
     *
     * @param entityType   点赞实体对象 1-帖子 2-评论
     * @param entityId     点赞对象id
     * @param entityUserId 赞的帖子/评论的作者 id
     * @param postId       帖子的 id (点赞了哪个帖子，点赞的评论属于哪个帖子，点赞的回复属于哪个帖子)
     * @return
     */
    @PostMapping("/like")
    public Result like(int entityType, int entityId, int entityUserId, int postId) {
        Object likeTargetEntity = likeService.getLikeTargetEntity(entityType, entityId);
        if(likeTargetEntity == null){
            return new Result("fail", "1", "点赞目标不存在");
        }

        JwtUser user = getUser();

        log.info("点赞用户: " + user.toString());
        // 点赞
        likeService.insertLike(user.getId(), entityType, entityId, entityUserId);
        // 点赞数量
        long likeCount = likeService.findEntityLikeCount(entityType, entityId);
        // 点赞状态
        int likeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);

        Map<String, Object> map = new HashMap<>();
        map.put("likeCount", likeCount);
        map.put("likeStatus", likeStatus);

        String userIdOfLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        // 触发点赞事件（系统通知） - 取消点赞不通知、重复点赞不通知、自己点赞自己不通知
        if (likeStatus == 1 && !redisTemplate.opsForSet().isMember(userIdOfLikeKey, user.getId()) && entityUserId != getUser().getId()) {
            Event event = new Event()
                    .setTopic(TOPIC_LIKE)
                    .setUserId(getUser().getId())
                    .setEntityType(entityType)
                    .setEntityId(entityId)
                    .setEntityUserId(entityUserId)
                    .setData("postId", postId);
            eventProducer.fireEvent(event);

            // 新增实体对应的点赞 userId
            redisTemplate.opsForSet().add(userIdOfLikeKey, user.getId());
        }

        // 触发增加经验事件
        Event event = new Event()
                .setTopic(TOPIC_EXP)
                .setUserId(user.getId())
                .setData("type", ExpType.EXP_LIKE.getName());
        eventProducer.fireEvent(event);

        if (entityType == ENTITY_TYPE_POST) {
            // 计算帖子分数
//            String redisKey = RedisKeyUtil.getPostScoreKey();
//            redisTemplate.opsForSet().add(redisKey, postId);
            discussPostService.addDisscussPostToRefreshScore(postId);
        }

        return new Result("success", Result.SUCCESS, map);
    }

}
